package com.unitlib.net.parser;

import com.unitlib.net.bean.Response;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.lang.reflect.Type;

import rxhttp.wrapper.annotation.Parser;
import rxhttp.wrapper.entity.ParameterizedTypeImpl;
import rxhttp.wrapper.exception.ParseException;
import rxhttp.wrapper.parse.AbstractParser;

@Parser(name = "Response")
public class ResponseParser<T> extends AbstractParser<T> {

    private static final String TAG = "ResponseParser";

    protected ResponseParser() {
        super();
    }

    public ResponseParser(Type type) {
        super(type);
    }

    @SuppressWarnings("unchecked")
    @Override
    public T onParse(@NotNull okhttp3.Response response) throws IOException {
        Type type = ParameterizedTypeImpl.get(Response.class, mType); //获取泛型类型
        Response<T> data = convert(response, type);
        T t = data.getData(); //获取data字段
        if (t == null && mType == String.class) {
            t = (T) data.getReturn_message();
        }
        if (!data.getReturn_code().equals("000000")) { //code不等于000000，说明数据不正确，抛出异常
            throw new ParseException(data.getReturn_code(), data.getReturn_message(), response);
        }
        return t;
    }
}
